// 2025/10/21
// 二叉树锯齿形层序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        if(root == nullptr)
            return ans;
        stack<TreeNode*> st_1, st_2;
        st_1.emplace(root);
        while(!st_1.empty() || !st_2.empty())
        {
            vector<int> tmp;
            if(!st_1.empty())
            {
                while(!st_1.empty())
                {
                    TreeNode *cur = st_1.top();
                    st_1.pop();
                    tmp.emplace_back(cur->val);
                    if(cur->left)
                        st_2.emplace(cur->left);
                    if(cur->right)
                        st_2.emplace(cur->right);
                }
            }
            else
            {
                while(!st_2.empty())
                {
                    TreeNode *cur = st_2.top();
                    st_2.pop();
                    tmp.emplace_back(cur->val);
                    if(cur->right)
                        st_1.emplace(cur->right);
                    if(cur->left)
                        st_1.emplace(cur->left);
                }
            }
            ans.push_back(tmp);
        }
        return ans;
    }
};